#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
//结构体
typedef struct Usr
{
	int IID;
	char NName[32];
	int AAge;
	float MMoney;

	struct Usr *next;
}Usr;
typedef struct List
{
	int LLen;
	Usr *pFirstNode;
}List;
//申请空间
Usr *mkUsrNode()
{
	Usr *node = (Usr*)malloc(sizeof(Usr));
	if (NULL == node)
	{
		exit(EXIT_FAILURE);
	}
	memset(node, 0, sizeof(Usr));
	return node;
}
List *mkList()
{
	List *list = (List*)malloc(sizeof(List));
	if (NULL == list)
	{
		exit(EXIT_FAILURE);
	}
	memset(list, 0, sizeof(List));
	return list;
}
//插入数据，生成链表
void insert(List *list, Usr *node)
{
	if (NULL == list || NULL == node)
	{
		return;
	}
	node->next = list->pFirstNode;
	list->pFirstNode = node;	
	list->LLen++;
}
//输出
void display(const List *list)
{
	if (NULL == list)
	{
		return;
	}

	Usr *node = list->pFirstNode;
	while (NULL != node)
	{
		printf("id=%d,name=%s,age=%d,money=%.1f\n"
			   , node->IID, node->NName, node->AAge
			   , node->MMoney);
		node = node->next;
	}
}
//排序
void sortByAge(List *list)
{
	if (NULL == list)
	{
		return;
	}
	Usr *pre = NULL;
	Usr *cur = NULL;
	int i=0;
	int j=0;
	for (; i<list->LLen; i++)
	{
		pre = list->pFirstNode;
		cur = pre;
		for (j=0; j<list->LLen-1; j++)
		{
			if (cur->AAge > cur->next->AAge)
			{
				if (cur == list->pFirstNode)
				{
					list->pFirstNode = cur->next;	
					cur->next = cur->next->next;
					list->pFirstNode->next = cur;
					pre = list->pFirstNode;
					continue;
				}
				else
				{
					pre->next = cur->next;
					cur->next = cur->next->next;	
					pre->next->next = cur;
					pre = pre->next;
					continue;
				}
			}	
			pre = cur;
			cur = cur->next;
		}
	}
}
//加载文件数据，生成链表
void load(List *list, const char *path)
{
	if (NULL == list || NULL == path)
	{
		return;
	}
	FILE *file = fopen(path, "r");
	Usr *node = NULL;
	int ret = 0;
	while (1)
	{
		node = mkUsrNode();
		ret = fscanf(file, "%d%s%d%f", &node->IID
					     , node->NName
						 , &node->AAge, &node->MMoney);
		if (0 >= ret)
		{
			free(node);
			node = NULL;
			fclose(file);
			break;
		}
		insert(list, node);
	}
}
int main(int argc, char *argv[])
{	
	if (2 != argc)
	{
		exit(EXIT_FAILURE);
	}
	List *list = mkList();
	load(list, argv[1]);
	display(list);
	sortByAge(list);
	printf("----------------------\n\n");
	printf("按照年龄排序后：\n");
	display(list);
	return 0;
}
